package mysql

import (
	"context"
	"cs0512/fmr/pkg/model"

	"gorm.io/gorm"
)

type userStore struct {
	db *gorm.DB
}

func newUserStore(ds *datastore) *userStore {
	return &userStore{db: ds.db}
}

func (us *userStore) Create(ctx context.Context, userModel *model.User) error {
	return us.db.Save(userModel).Error
}

func (us *userStore) Update(ctx context.Context, userModel *model.User) error {
	err := us.db.Save(userModel).Error
	return err
}

func (us *userStore) Delete(ctx context.Context, id int) error {
	userModel := model.User{
		ID: id,
	}
	err := us.db.Delete(userModel).Error
	return err
}

func (us *userStore) Get(ctx context.Context, id int) (*model.User, error) {
	u := &model.User{
		ID: id,
	}
	if err := us.db.First(u).Error; err != nil {
		return nil, err
	}
	return u, nil
}

func (us *userStore) GetByUsername(ctx context.Context, username string) (*model.User, error) {
	u := &model.User{
		Username: username,
	}
	if err := us.db.Where("username=?", username).First(u).Error; err != nil {
		return nil, err
	}
	return u, nil
}

func (us *userStore) List(ctx context.Context, opts model.UserOptions) (*model.UserList, error) {
	list := &model.UserList{
		Items: make([]*model.User, 0),
	}
	var total int64
	var err error

	query := us.db.Model(&model.User{})
	if opts.Uid > 0 {
		query = query.Where("id = ?", opts.Uid)
	}
	if opts.Username != "" {
		query = query.Where("username like ?", "%"+opts.Username+"%")
	}
	if opts.Status > 0 {
		query = query.Where("status = ?", opts.Status)
	}

	if opts.Size > 0 {
		err = query.Offset(opts.GetOffset()).Limit(opts.Size).Find(&list.Items).Offset(-1).Limit(-1).Count(&total).Error
	} else {
		err = query.Find(&list).Count(&total).Error
	}

	if err != nil {
		return nil, err
	}

	list.ListMeta = model.NewListMeta(int(total), opts.Size)

	return list, nil
}
